<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\Console;

/**
 * 初始化类型数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200900_001200_u_staff extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%staff}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->compact = true;
        $data = $this->getData('staff.php');
        $count = count($data);
        Console::startProgress($i = 0, $count);
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        foreach ($data as $staffId => $item) {
            list($realname, $mobile, $companyId) = $item;
            $uniMobile = $security->generatePrivateKey($mobile);
            $i++;
            Console::updateProgress($i, $count);
            $staff = (new Query())->from($this->tableName)->andWhere(['id' => $staffId])->one();
            if (!$staff) {
                continue;
            }
            $attributes = [
                'realname' => $realname,
                'mobile' => $uniMobile,
                'mobile_hash' => $security->encryptMaster($mobile),
                'company_id' => intval($companyId),
            ];
            $this->update($this->tableName, $attributes, [
                'id' => $staff['id']
            ]);
            if ($staff['user_id']) {
                $attributes['nickname'] = $realname;
                $this->update('{{%user}}', $attributes, [
                    'id' => $staff['user_id']
                ]);
            }
        }
        Console::endProgress("update done." . PHP_EOL);
    }

}
